package com.uy.system.common.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.uy.system.common.constant.SystemConstants;
import com.uy.system.distribute.DistributedCacheService;
import com.uy.system.distribute.redis.RedisDistributedCacheService;
import com.uy.system.model.entity.SysUser;
import com.uy.system.service.ISysUserService;
import com.uy.system.service.impl.SysUserServiceImpl;
import java.util.concurrent.TimeUnit;

/**
 * @Author LY
 * @create 2024/4/24 16:14
 * @Description 用户信息存储
 */
public class SessionUtils {

    private static DistributedCacheService distributedCacheService = SpringUtils.getBean(RedisDistributedCacheService.class);
    private static ISysUserService iSysUserService = SpringUtils.getBean(SysUserServiceImpl.class);

    /**
     * 缓存用户信息
     */
    public static void cacheSysUser(SysUser user){
        String key = SystemConstants.SYS_USER_KEY + user.getUserId();
        distributedCacheService.set(key, user, SystemConstants.CACHE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 获取用户信息
     */
    public static SysUser getSysUser(){
        String key = SystemConstants.SYS_USER_KEY + getUserId();
        SysUser sysUser = distributedCacheService.getObject(key, SysUser.class);
        if (sysUser == null){
            sysUser = iSysUserService.findSysUserByUserId(Long.valueOf(getUserId()));
            distributedCacheService.set(key, sysUser, SystemConstants.CACHE_TIME, TimeUnit.SECONDS);
        }
        return sysUser;
    }

    /**
     * 移除用户缓存信息
     */
    public static void removeSysUser(){
        String key = SystemConstants.SYS_USER_KEY + getUserId();
        distributedCacheService.delete(key);
    }

    /**
     * 获取当前登录用户id
     */
    public static String getUserId(){
        String userId = StpUtil.getLoginIdAsString();
        if (StrUtil.isBlank(userId)){
            throw new RuntimeException("用户id不存在");
        }
        return userId;
    }
}
